package rules.tree;
import org.jdom.*;
import org.jdom.input.SAXBuilder;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;


public class Mapping {
    private SAXBuilder builder;
    private Document doc;
    private Element root,rule,mapping,target,source;
    private ArrayList<Rule> rules = new ArrayList<Rule>();

    public Mapping(FileInputStream file) throws JDOMException, IOException {
            builder = new SAXBuilder();
            doc = builder.build(file);
            root = doc.getRootElement();
            mapping = root.getChild("mappingRules");
            target = root.getChild("ontoTarget");
            source = root.getChild("ontoSource");
    }

    public Mapping(){
        builder = new SAXBuilder();
        doc = new Document();
        root = new Element("mapping");
        source = new Element("ontoSource");
        source.addContent(new Element("location"));
        root.addContent(source);
        target = new Element("ontoTarget");
        target.addContent(new Element("location"));
        root.addContent(target);
        mapping = new Element("mappingRules");
        root.addContent(mapping);
        doc.setRootElement(root);

        rules = new ArrayList<Rule>();
    }

    // Esse metodo deve declarar o namespace das ontologias fonte e alvo
    public void setRoot(Namespace srcNamespace, Namespace tgtNamespace){
       
    }

    public void setSourceURI(String uri){
        source.setAttribute("URI", uri);
    }

     public void setTargetURI(String uri){
        target.setAttribute("URI", uri);
    }

     public void setSourceLocation(String location){
        source.getChild("location").setText(location);
    }

     public void setTargetLocation(String location){
        target.getChild("location").setText(location);
    }

    public ArrayList<Rule> getRules(){
        List list = mapping.getChildren();
        Iterator iterator = list.iterator();
        Element temp;
        while (iterator.hasNext()) {
            rule = (Element) iterator.next();
            Rule r = new Rule(rule);
            rules.add(r);
          }
        return rules;
    }

    public Element getRoot(){
        return root;
    }

    public String getLocationSource(){
            return source.getChild("location").getValue();
    }

    public String getLocationTarget(){
            return target.getChild("location").getValue();
    }

    public String getOntoSource(){
            return source.getAttributeValue("URI");
    }

    public String getOntoTarget(){
            return target.getAttributeValue("URI");
    }

    public void addRule(Rule r){
        mapping.addContent(r.getElement());
        rules.add(r);
    }

    public Document getDoc(){
        return doc;
    }

   
}